package cn.learn.controller;

import cn.learn.properties.MySecurityConstants;
import cn.learn.properties.SecurityProperties;
import cn.learn.util.RestResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 游览器的登录页面跳转逻辑
 *
 * @author huangyezhan
 * @date 2020年02月22日13:48
 */
@RestController
public class BrowserSecurityLoginController {
    private static final Logger logger = LoggerFactory.getLogger(BrowserSecurityLoginController.class);

    /**
     * 当前请求已经缓存到session里面去了
     * 用请求缓存对象再拿出来
     */
    private RequestCache     requestCache     = new HttpSessionRequestCache();
    /**
     * 重定向
     */
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    /**
     * 动态配置
     */
    @Autowired
    private SecurityProperties securityProperties;


    @RequestMapping(value = MySecurityConstants.DEFAULT_UNAUTHENTICATION_URL, method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public RestResponse loginAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        if (savedRequest != null) {
            String redirectUrl = savedRequest.getRedirectUrl();
            logger.info("引发跳转请求的路径是：{}", redirectUrl);
            if (StringUtils.endsWithIgnoreCase(redirectUrl, ".html")) {
                //重定向到指定的html页面
                redirectStrategy.sendRedirect(request, response, securityProperties.getBrowser().getLoginPage());
            }
        }
        //如果不是html则往下执行
        return RestResponse.failed(String.valueOf(HttpStatus.UNAUTHORIZED.value()), "访问的服务需要认证，引导用户到登录页面");
    }


}
